import config from '../config.js'

import update from './functions/mpweixin/update.js'
import bluetooth from './functions/bluetooth.js'
import device from './functions/device.js'
// import file from './functions/file.js'
// import image from './functions/image.js'
import location from './functions/location.js'
import other from './functions/other.js'
import pay from './functions/pay.js'
import permission from './functions/permission.js'
// import record from './functions/record.js'
import run from './functions/run.js'
// import video from './functions/video.js'
import tip from './functions/tip.js'

let common = {}

// 自定义tabBar设置索引
common.setTabBarIndex = other.setTabBarIndex
// 打开内置地图
common.openLocation = location.openLocation
// 获取当前的地理位置
common.getLocation = location.getLocation
// 拨打电话
common.callPhone = device.callPhone
// 请求支付
common.requestPayment = pay.requestPayment
// 微信小程序管理版本更新
common.update = update
// 界面交互
common.tip = tip

/**
 * 项目主色
 * 2021-03-01
 */
common.mainColor = function() {
	return config.mainColor
}

/**
 * 获取浏览器
 * 2020-08-11
 */
common.userBroswer = function() {
	// #ifdef H5
	let user_agent = navigator.userAgent.toLowerCase()
	if (user_agent.indexOf('micromessenger') > 0) {
		return 'weixin'
	} else if (user_agent.indexOf('alipay') > 0) {
		return 'alipay'
	} else {
		return 'other'
	}
	// #endif

	// #ifndef H5
	return ''
	// #endif
}

/**
 * 获取环境
 * 2020-08-11
 */
common.userAgent = function() {
	// #ifdef H5
	let user_agent = navigator.userAgent.toLowerCase()
	if (user_agent.indexOf('micromessenger') > 0) {
		if (config.weixinAuth) {
			return 'weixin'
		} else {
			return 'h5'
		}
	} else if (user_agent.indexOf('alipay') > 0) {
		if (config.alipayAuth) {
			return 'h5_alipay'
		} else {
			return 'h5'
		}
	} else {
		if (config.isTest) {
			return config.testUserAgent
		}
		return 'h5'
	}
	// #endif

	// #ifdef APP-PLUS
	return 'app'
	// #endif

	// #ifdef MP-WEIXIN
	return 'mp_weixin'
	// #endif

	// #ifdef MP-QQ
	return 'mp_qq'
	// #endif

	// #ifdef MP-ALIPAY
	return 'mp_alipay'
	// #endif

	// #ifdef MP-TOUTIAO
	return 'mp_toutiao'
	// #endif

	return ''
}

/**
 * 获取当前时间戳
 * 2022-02-16
 */
common.curTimestamp = function() {
	return Date.parse(new Date()) / 1000
}


/**
 * 获取客户端平台，值域为：ios、android
 * 2021-03-01
 */
common.platform = function() {
	let info = uni.getSystemInfoSync()
	return info.osName
}

/**
 * 获取客户端平台，值域为：ios、android
 * 2021-03-01
 */
common.isLogin = function() {
	let user_id = uni.getStorageSync('user_id')
	if (user_id == '' || user_id == 0) {
		return false
	} else {
		return true
	}
}


/**
 * 解析URL 参数
 * @param {string} name 参数名
 * 2020-08-17
 */
common.getUrlParam = function(name) {
	let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
	let r = window.location.search.substr(1).match(reg)
	if (r != null) {
		return unescape(r[2])
	}
	return null
}


/**
 * 模拟alert弹窗
 * @param {string} content 内容
 * 2020-08-17
 */
common.alert = function(content) {
	return new Promise((resolve, reject) => {
		uni.showModal({
			title: '',
			content: content,
			showCancel: false,
			success(res) {
				resolve(res)
			},
			fail(res) {
				reject(res)
			}
		})
	})
}


/**
 * 模拟confirm弹窗
 * @param {string} content 内容
 * @param {string} cancelText 取消文案
 * @param {string} confirmText 确定文案
 * 2020-08-17
 */
common.confirm = function(content, cancelText = "取消", confirmText = "确定") {
	return new Promise((resolve, reject) => {
		uni.showModal({
			title: '',
			content: content,
			showCancel: true,
			cancelText: cancelText,
			confirmText: confirmText,
			success(res) {
				resolve(res)
			},
			fail(res) {
				reject(res)
			}
		})
	})
}


/**
 * 提示
 * @param {string} message 内容
 * 2020-08-17
 */
common.toast = function(message) {
	uni.showToast({
		title: message,
		icon: 'none',
		// #ifdef APP|MP-WEIXIN
		mask: true
		// #endif
	})
}




/**
 * 设置页面标题
 * @param {string} title 页面标题
 * 2021-03-01
 */
common.setTitle = function(title = '') {
	uni.setNavigationBarTitle({
		title: title
	})
}

/**
 * 获取文件后缀，带'.'
 * @param {string} filename 文件路径
 * 2021-03-01
 */
common.getSuffix = function(filename) {
	let pos = filename.lastIndexOf('.')
	let suffix = ''
	if (pos != -1) {
		suffix = filename.substring(pos)
	}
	return suffix
}

/**
 * 获取随机字符串
 * @param {number} length 字符串长度
 * 2021-03-01
 */
common.getRandomStr = function(length = 32) {
	let chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
	let maxPos = chars.length
	let pwd = ''
	for (let i = 0; i < length; i++) {
		pwd += chars.charAt(Math.floor(Math.random() * maxPos))
	}
	return pwd
}


/**
 * 把一个数组按照一定长度分割成若干数组
 * @param {array} array 数组
 * @param {number} length 子数组的长度
 * 2020-08-17
 */
common.arrayGroup = function(array, length) {
	let index = 0
	let newArray = []
	while (index < array.length) {
		newArray.push(array.slice(index, index += length))
	}
	return newArray
}


/**
 * 获取日期时间
 * @param {number} number 几天之后
 * 2021-03-01
 */
common.getDate = function(number = 0) {
	let date = new Date()
	date.setTime(date.getTime() + number * 24 * 60 * 60 * 1000)
	return date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate()
}


/**
 * 手机号中间4为加星
 * @param {number} mobilePhone 手机号
 * 2021-03-01
 */
common.mobilePhoneSafe = function(mobilePhone) {
	return mobilePhone.substring(0, 3) + '****' + mobilePhone.substring(7, 11)
}

/**
 * px转换为rpx
 * @param {number} number px
 * 2021-03-01
 */
common.px2rpx = function(number) {
	const systemInfo = uni.getSystemInfoSync()
	return number * (750 / systemInfo.screenWidth)
}

/**
 * rpx转换为px
 * @param {number} number rpx
 * 2021-03-01
 */
common.rpx2px = function(number) {
	const systemInfo = uni.getSystemInfoSync()
	return number * (systemInfo.screenWidth / 750)
}

/**
 * 倒计时 TODO
 * @param {number} second 秒数
 * @param {number} type 1--最大划分到秒 2最大划分到分钟 3--最大划分到小时 4--最大划分到天
 * 2021-03-01
 */
common.timeSplit = function(second, type = 3) {
	if (second < 0) {
		return false
	}

	let obj = {}
	if (type == 2) {
		obj.minute = Math.floor(second / 60)
		obj.second = second - obj.minute * 60

		obj.minute = obj.minute < 10 ? '0' + obj.minute : obj.minute
		obj.second = obj.second < 10 ? '0' + obj.second : obj.second
	} else if (type == 3) {
		obj.hour = Math.floor(second / 3600)
		obj.minute = Math.floor((second - obj.hour * 3600) / 60)
		obj.second = second - obj.hour * 3600 - obj.minute * 60

		obj.hour = obj.hour < 10 ? '0' + obj.hour : obj.hour
		obj.minute = obj.minute < 10 ? '0' + obj.minute : obj.minute
		obj.second = obj.second < 10 ? '0' + obj.second : obj.second
	}

	return obj
}

/**
 * 获取多张图片信息
 * @param {array} images 图片
 * callBack: 成功的回调函数
 */
common.getImagesInfo = function(images, callBack = function() {}, images_path = []) {
	if (images.length > 0) {
		var image = images.shift()
		this.getImageInfo(image, (res) => {
			images_path.push(res.path)
			this.getImagesInfo(images, callBack, images_path)
		})
	} else {
		var obj = {}
		obj.path = images_path
		callBack(obj)
	}
}

/**
 * 获取图片信息
 * image:  图片
 * callBack: 成功的回调函数
 */
common.getImageInfo = function(image, callBack = function() {}) {
	uni.getImageInfo({
		src: image,
		success(res) {
			callBack(res)
		}
	})
}


/**
 * 监听首页退出应用
 * urls tabbar页面路径
 * 2021-12-29
 */
common.listenBackButtonQuitApp = function(urls = []) {

	let user_agent = this.userAgent()
	if (user_agent = 'app') {
		let platform = this.platform()
		if (platform == 'android') { //如果是android
			//监听手机安卓返回键退出APP
			let back_button_press = 0
			plus.key.addEventListener('backbutton', () => {

				//获取地址栏目中的url
				var pages = getCurrentPages()
				var page = pages[pages.length - 1]
				var route = page.route

				if (urls.indexOf(route) > -1) {
					back_button_press++

					if (back_button_press > 1) {
						plus.runtime.quit()
					} else {
						plus.nativeUI.toast('再按一次退出应用')
					}
					setTimeout(() => {
						back_button_press = 0
					}, 1000)
				}

			})

		}
	}
}

/**
 * 重写当前页面路由以兼容微信公众号支付
 * 2022-04-29
 */
common.curUrlReload = function() {
	let url = window.location.href
	if (!url.match(/\?#/)) {
		console.log(window.location.href.split('#')[0] + '?' + window.location.hash)
		window.location.replace(window.location.href.split('#')[0] + '?' + window.location.hash)
	}
}



export default common
